<template>
  <div class="apply-dialog">
    <el-dialog title="" :visible.sync="dialogVisible" :fullscreen="true" :before-close="handleClose" :close-on-click-modal="false" :show-close="false">
      <LimitTech ref="LimitTech" @showTech="openTech" />
      <Tech ref="Tech" @showLimit="openHelp" />
      <div slot="title" class="flex flex-row align-center justify-content-end">
        <div class="btn-list flex flex-row align-center">
          <el-button type="primary" size="mini" :disabled="submitDisabled" @click="submitAction">保存</el-button>
          <div class="ml50" @click="handleClose"><i class="el-icon-close cursor-p font22 line-height-32" /></div>
        </div>
      </div>
      <div id="pdfHtml" class="app-container">
        <el-card class="box-card apply-box mt10 mb20">
          <el-form ref="generateForm" label-suffix=":" size="small" :model="models" :rules="rules" label-position="right" label-width="100px">
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="技术名称" prop="name" label-width="130px">
                  <el-input v-model="models.name" :style="{width:'100%'}" placeholder="请输入技术名称" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="准入文号" prop="approvalNumber">
                  <el-input v-model="models.approvalNumber" :style="{width:'100%'}" placeholder="请输入准入文号" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="详细目录" prop="detailContents" label-width="130px">
                  <el-input v-model="models.detailContents" :style="{width:'100%'}" placeholder="请输入详细目录" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="准入日期">
                  <el-date-picker v-model="models.fillTime" :style="{width:'100%'}" type="datetime" placeholder="准入日期" value-format="yyyy-MM-dd HH:mm:ss" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="技术类别" prop="projectClass" label-width="130px">
                  <el-select v-model="models.techType" :style="{width:'100%'}" placeholder="请选择项目分类" :filterable="false" clearable>
                    <el-option v-for="(item, index) in techTypeList" :key="index" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="申请科室" prop="applyDeptId">
                  <el-select v-model="models.applyDeptId" :style="{width:'100%'}" placeholder="请选择科室" :filterable="false" clearable value="" @change="handleChange">
                    <el-option v-for="(item) in structureList" :key="item.id" :value="item.id" :label="item.depName" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="项目分类" prop="projectClass" label-width="130px">
                  <el-select v-model="models.projectClass" :style="{width:'100%'}" placeholder="请选择项目分类" :filterable="false" clearable value="">
                    <el-option v-for="(item, index) in projectClassList" :key="index" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="科室负责人" prop="applyManagerName">
                  <el-input v-model="models.applyManagerName" :style="{width:'100%'}" placeholder="自动带入" disabled />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="是否年审" prop="needYearAudit" label-width="130px">
                  <el-select v-model="models.needYearAudit" :style="{width:'100%'}" placeholder="是否年审" :filterable="false" clearable>
                    <el-option v-for="(item, index) in isAnnual" :key="index" :value="item.value" :label="item.label" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="16">
                <el-form-item label="相关附件：" prop="applyDocs" label-width="130px">
                  <FileUpload :element="uploadConfig" :preview="false" @fileList="fileList" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </el-card>
        <el-card v-for="(item, index) in models.annualHis" :key="index" style="position: relative" class="box-card apply-box mt10 mb20">
          <el-form label-suffix=":" size="small" label-position="left" label-width="100px">
            <el-row type="flex" :gutter="30" justify="start" align="top">
              <el-col :span="8">
                <el-form-item label="年审时间" label-width="100px">
                  <el-date-picker v-model="item.annualYear" :style="{width:'100%'}" type="year" value-format="yyyy" placeholder="年审时间" />
                </el-form-item>
              </el-col>
              <el-col :span="10">
                <el-form-item label="年审附件" prop="annualDocs" label-width="100px">
                  <FileUpload :element="uploadConfig" :preview="false" :index="index" @fileList="fileListArr" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="delete"><el-button type="danger" @click="handlerDel(index)">删除当前年审记录</el-button></div>
        </el-card>
        <el-card class="box-card apply-box mt10 mb20">
          <div class="addBtn"><el-button type="primary" @click="handlerAdd">添加年审记录</el-button></div>
        </el-card>
      </div>
    </el-dialog>
    <LeaderDialog ref="leaderRef" @selectLeader="selectLeader" />
  </div>
</template>

<script>
import Vue from 'vue'
import { GenerateForm } from '@/components/VueFormMaking'
import FileUpload from '@/components/VueFormMaking/components/Upload/file.vue'
import 'form-making/dist/FormMaking.css'
Vue.component(GenerateForm.name, GenerateForm)
import LimitTech from './limitTech/index.vue'
import LeaderDialog from './leader/index.vue'

import Tech from './tech/index.vue'
import {
  processStructure,
  createWorkOrder,
  updateWorkOrder,
  recallWorkOrder,
  newCreateWorkOrder,
  newHistoryYearAudit
} from '@/api/xjs/work-order'
import { listAllUser, newListUser } from '@/api/system/sysuser'
import { getOrdinaryDeptList, newTreeselect, getNewDeptList, getNewDeptInfo } from '@/api/system/dept'
import { mapGetters } from 'vuex'
import { projectClassList, techTypeList, isAnnual } from '@/utils/common'
import { Loading } from 'element-ui'
import { newGetUserInfo } from '@/api/user'
export default {
  name: 'ApplyDialog',
  components: {
    FileUpload,
    LimitTech,
    Tech,
    LeaderDialog
  },
  props: {
    value: {
      type: String,
      default: ''
    },
    listData: {
      type: Object,
      default() {
        return {}
      }
    }
  },
  data() {
    return {
      models: {
        name: '', // 技术名称
        approvalNumber: '', // 准入文号
        detailContents: '', // 详情目录
        fillTime: '', // 准入日期
        techType: null, // 技术类别
        applyDeptId: null, // 申请科室
        projectClass: null, // 项目分类
        applyManagerName: null, // 科室负责人
        needYearAudit: null, // 是否年审
        applyDocs: null, // 相关附件
        annualHis: []
      },
      annualObj: {
        annualDocs: null, // 年审附件
        annualYear: null // 年审时间
      },
      fileIndex: 2,
      projectClassList: projectClassList,
      techTypeList: techTypeList,
      isAnnual: isAnnual,
      searchPriceNo: '',
      auditStatus: 1,
      printData: {
        printable: 'printFrom',
        header: '',
        ignore: ['no-print']
      },
      workOrdeInfo: {
        id: null
      },
      uploadConfig: {
        options: {
          defaultValue: [],
          disabled: false,
          length: 9,
          tip: '',
          width: '50%'
        }
      },
      uploadConfig1: {
        options: {
          defaultValue: [],
          disabled: false,
          length: 9,
          tip: '三证为:《医疗器械生产企业许可证》、《医疗器械注册证》和《医疗器械经营企业许可证》。',
          width: '50%'
        }
      },
      limitTechList: [],
      selectLimitData: [],
      loading: false,
      dialogVisible: false,
      limitTechVisible: false,
      submitDisabled: false,
      draftDisabled: false,
      recallDisabled: false,
      downloadVisible: false,
      active: 0,
      total: 0,
      structureList: [],
      structureUserList: [],
      userList: [],
      processStructureValue: {},
      queryParams: {
        pageIndex: 1,
        pageSize: 5,
        name: undefined
      },
      tpls: [],
      newTpls: [],
      ruleForm: {
        workOrderId: 0,
        title: '',
        projectNo: '',
        process: '',
        classify: '',
        state: [],
        source: '',
        source_state: '',
        process_method: '',
        tpls: {
          form_structure: [],
          form_data: []
        },
        newTpls: {},
        tasks: [],
        status: 0
      },
      rules: {
        // title: [{ required: true, message: '请输入工单标题', trigger: 'blur' }]
      },
      remoteFunc: {
        // 获取用户列表
        async userList(resolve) {
          const res = await listAllUser({})
          const options = res.data
          resolve(options)
        },
        async deptTreeList(resolve) {
          const res = await getOrdinaryDeptList()
          resolve(res.data)
        }
      }
    }
  },
  computed: {
    ...mapGetters(['name', 'newUserInfo', 'globalConfig']),
    orderState() {
      if (this.workOrdeInfo.id != null) {
        if (this.workOrdeInfo.status == 1) {
          return '未提交(草稿)'
        } else {
          return `${this.workOrdeInfo.current_state_name}【${
            this.workOrdeInfo.principals
          }】`
        }
      } else {
        return '未提交'
      }
    }
  },
  created() {
    console.log(11111, this.listData)
    // this.getNewDeptTreeList()
  },
  methods: {
    // 添加年审记录
    handlerAdd() {
      const obj = JSON.parse(JSON.stringify(this.annualObj))
      this.models.annualHis.push(obj)
      console.log(this.models)
      this.$forceUpdate()
    },
    // 删除年审记录
    handlerDel(index) {
      this.models.annualHis.splice(index, 1)
      this.$forceUpdate()
    },
    fileList(files) {
      this.models.applyDocs = JSON.stringify(files)
    },
    fileListArr(item) {
      this.models.annualHis[item.index].annualDocs = JSON.stringify(item.files)
    },
    handleChange(v) {
      getNewDeptInfo({ id: v }).then(res => {
        this.models.applyManagerName = res.records[0].deptManagerName
      })
    },
    downLoadDoc(type) {
      var a = document.createElement('a')
      switch (type) {
        case 1:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（操作技术）.docx`
          break
        case 2:
          a.href =
            `/${this.globalConfig.folderName}/非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          a.download =
            `非限制类使用——${this.globalConfig.fullName}医疗技术临床应用审核申请书（检验检查）.docx`
          break
        case 3:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 4:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
        case 5:
          a.href = '/static/xjs/限制类备案使用——新技术备案申请表（样表）.docx'
          a.download = '限制类备案使用——新技术备案申请表（样表）.docx'
          break
      }
      a.style.display = 'none'
      document.body.appendChild(a)
      a.click()
      a.remove()
    },
    openHelp() {
      this.$refs.Tech.close()
      this.$refs.LimitTech.open()
    },
    openTech() {
      this.$refs.LimitTech.close()
      this.$refs.Tech.open()
    },

    handlePrint(params) {
      /* printJS({
        maxWidth: 1920,
        documentTitle: '甘肃省人民医院医务一网通办',
        printable: params.printable, // 'printFrom',
        type: params.type || 'html',
        header: params.header, // '表单',
        targetStyles: ['*'],
        ignoreElements: params.ignore || [], // ['no-print']
        properties: params.properties || null
      })*/

      const vm = this
      const A4_WIDTH = 592.28
      const A4_HEIGHT = 841.89 // $myLoading 自定义等待动画组件，实现导出事件的异步等待交互
      this.pdfLoading = true
      this.loadingFull = Loading.service({
        target: document.querySelector('.app-wrapper'),
        lock: true,
        text: '正在导出中，请稍后……',
        background: 'rgba(0, 0, 0, 0.7)',
        customClass: 'zIndex9999'
      })
      vm.$nextTick(() => {
        // dom的id。
        const target = document.getElementById('pdfHtml')
        const pageHeight = target.scrollWidth / A4_WIDTH * A4_HEIGHT
        // 获取分割dom，此处为class类名为item的dom
        const lableListID = document.getElementsByClassName('item-excel')
        // 进行分割操作，当dom内容已超出a4的高度，则将该dom前插入一个空dom，把他挤下去，分割
        for (let i = 0; i < lableListID.length; i++) {
          const multiple = Math.ceil((lableListID[i].offsetTop + lableListID[i].offsetHeight / 2) / pageHeight)
          if (this.isSplit(lableListID, i, multiple * pageHeight)) {
            const divParent = lableListID[i].parentNode
            // 获取该div的父节点
            const newNode = document.createElement('div')
            newNode.className = 'emptyDiv'
            newNode.style.background = '#ffffff'
            const _H = multiple * pageHeight - (lableListID[i].offsetTop + lableListID[i].offsetHeight)
            newNode.style.height = _H + 30 + 'px'
            newNode.style.width = '100%'
            const next = lableListID[i].nextSibling
            // 获取div的下一个兄弟节点
            // // 判断兄弟节点是否存在
            if (next) {
              // 存在则将新节点插入到div的下一个兄弟节点之前，即div之后
              divParent.insertBefore(newNode, next)
            } else {
              // 不存在则直接添加到最后,appendChild默认添加到divParent的最后
              divParent.appendChild(newNode)
            }
          }
        }
        // 传入title和dom标签，此处是 #content// 异步函数，导出成功后处理交互
        this.getPdf(`${this.models.name || '未知项目'}`, '#pdfHtml').then(() => {}).catch(() => {})
        setTimeout(() => {
          this.loadingFull.close()
          this.pdfLoading = false
        }, 2000)
        this.pdfLoading = false
      })
    },
    handleClose(val) {
      this.dialogVisible = false
      this.$emit('refreshTable')
    },
    open() {
      this.resetDialog()

      Promise.all([getNewDeptList({ pageSize: 1 }), newGetUserInfo(), getNewDeptList({ pageSize: 9999 }), newListUser({ pageSize: 9999 })]).then(resArr => {
        // console.log(11111,resArr)
        const [managerData, userInfoData, deptData] = resArr
        this.models.applyUserName = userInfoData.records[0].name
        this.models.workNumber = userInfoData.records[0].empNo
        this.structureList = deptData.records
        this.dialogVisible = true

        /* this.models.applyManagerId = managerData.records[0].manager

        const _list = userListData.records
        const _structureUserList = managerData.records.map(item=>{
          const _temp = _list.filter(it=>it.id===item.manager)
          return {
            ...item,
            name:_temp[0].name
          }
        })
        this.structureUserList = _structureUserList
        this.dialogVisible = true*/
      })

      // this.getProcessNodeList()
    },
    resetDialog() {
      Object.assign(this.$data, this.$options.data())
    },
    handleLeader() {
      this.$refs.leaderRef.handleInversion()
    },
    getProcessNodeList() {
      processStructure({
        processId: 67
      }).then(response => {
        this.processStructureValue = response.data
        this.currentNode = this.processStructureValue.nodes[0]
        this.processStructureValue.tpls[0].form_structure.list[1].options.disabled = true
      })
    },
    draftAction() {
      if (this.workOrdeInfo.id) {
        this.models.id = this.workOrdeInfo.id
      }
      newCreateWorkOrder(this.models).then((res) => {
        // this.selectLeader(111111)
        this.$message({
          type: 'success',
          message: '提交成功!'
        })
        if (!this.workOrdeInfo.id) {
          this.workOrdeInfo.id = res.records[0].id
        }
        this.auditStatus = 1
        this.draftDisabled = false
        // this.$router.push({ path: '/project/applyList' })
      })
      /* this.draftDisabled = true
      var stateMap = {}
      this.ruleForm.process = 67
      this.ruleForm.status = 1
      this.ruleForm.classify = this.processStructureValue.process.classify
      stateMap['id'] = item.target
      this.ruleForm.source_state = this.processStructureValue.nodes[
        this.active
      ].label

      for (var v of this.processStructureValue.nodes) {
        if (v.id === item.target) {
          if (v.assignType !== undefined) {
            stateMap['process_method'] = v.assignType
          }
          if (v.assignValue !== undefined) {
            stateMap['processor'] = Array.from(new Set(v.assignValue))
          }
          stateMap['label'] = v.label
          stateMap['desc'] = v.desc
          break
        }
      }
      this.ruleForm.state = [stateMap]

      this.ruleForm.tpls = {
        form_name: [],
        form_structure: [],
        form_data: []
      }

      var promiseList = []

      this.tpls = []
      for (var tpl of this.newTpls) {
        this.tpls.push({
          tplDataId: tpl.id,
          tplId: tpl.form_structure.id
        })
      }

      for (var tpl of this.processStructureValue.tpls) {
        tpl.form_structure.id = tpl.id
        this.ruleForm.tpls.form_structure.push(tpl.form_structure)
        this.ruleForm.tpls.form_name.push(tpl.name)
        promiseList.push(
          this.$refs['generateForm-' + tpl.id][0].getDataNoValidate()
        )
      }

      Promise.all(promiseList)
        .then(values => {
          this.ruleForm.source = this.processStructureValue.nodes[
            this.active
          ].id
          console.log(values)
          for (var item of values) {
            if (item.hasOwnProperty('project_name')) {
              this.ruleForm.title = item.project_name
            }
          }
          if (this.tpls.length > 0) {
            for (var tplDataIndex in this.tpls) {
              this.tpls[tplDataIndex].tplValue = values[tplDataIndex]
            }
            this.ruleForm.newTpls = this.tpls
          }

          this.ruleForm.tpls.form_data = values
          this.ruleForm.is_exec_task = item.isExecuteTask
          draftWorkOrder(this.ruleForm)
            .then(response => {
              if (response.code === 200) {
                console.log(response)
                this.$message({
                  type: 'success',
                  message: '暂存成功!'
                })
                this.workOrdeInfo = response.data.workOrder
                this.ruleForm.workOrderId = this.workOrdeInfo.id
                this.newTpls = response.data.tpls
                this.draftDisabled = false
                this.recallStatus = 0
                console.log(this.ruleForm)
              }
            })
            .catch(() => {
              this.draftDisabled = false
            })
        })
        .catch(() => {
          this.draftDisabled = false
        })*/
    },

    selectLeader(userId) {
      this.ruleForm.state[0]['processor'] = [userId]
      if (this.ruleForm.workOrderId > 0) {
        updateWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      } else {
        createWorkOrder(this.ruleForm)
          .then(response => {
            if (response.code === 200) {
              this.$message({
                type: 'success',
                message: '提交成功!'
              })
              this.workOrdeInfo = response.data.workOrder
              this.ruleForm.workOrderId = this.workOrdeInfo.id
              this.recallStatus = 0
              this.$router.push({ path: '/project/applyList' })
              // this.$router.push({ path: "/process/upcoming" });
            }
          })
          .catch(() => {
            this.submitDisabled = false
          })
      }
    },
    recallOrder() {
      this.recallDisabled = true
      const recallParams = {
        work_oroder_id: this.workOrdeInfo.id,
        process_id: this.workOrdeInfo.process
      }
      recallWorkOrder(recallParams)
        .then(response => {
          if (response.code === 200) {
            this.$message({
              type: 'success',
              message: '撤回成功!'
            })
            this.workOrdeInfo = response.data.workOrder
            this.ruleForm.workOrderId = this.workOrdeInfo.id
            this.recallDisabled = false
            this.recallStatus = 1
            // this.$router.push({ path: "/process/upcoming" });
          }
        })
        .catch(() => {
          this.recallDisabled = false
        })
    },
    submitAction(item) {
      newHistoryYearAudit(this.models).then(res => {
        console.log('提交', res)
        this.$message({
          type: 'success',
          message: '提交成功!'
        })
        // this.auditStatus = 2
        this.submitDisabled = false
        this.handleClose()
      })
      /* if(this.workOrdeInfo.id){
        newDoUpdate({id:this.workOrdeInfo.id}).then(res=>{

          console.log("提交",res)

          this.$message({
            type: 'success',
            message: '提交成功!'
          })
          // this.auditStatus = 2
          this.submitDisabled = false
          this.$router.push({ path: '/xjsxxm/apply/myApply' })

        })
      } else {
        newCreateWorkOrder(this.models).then((res)=>{
          const id = res.records[0].id;
          newDoUpdate({id}).then(res=>{

            console.log("提交",res)

            this.$message({
              type: 'success',
              message: '提交成功!'
            })
            // this.auditStatus = 2
            this.submitDisabled = false
            this.$router.push({ path: '/xjsxxm/apply/myApply' })

          })

        })
      }*/
    }
  }
}
</script>

<style lang="scss" scoped>
/* 去掉全选按钮 */
::v-deep .el-table .disabledCheck .cell .el-checkbox__inner {
    display: none !important;
}

::v-deep .el-table .disabledCheck .cell::before {
    content: "请选择";
    text-align: center;
    line-height: 37px;
}
.delete {
    position: absolute;
    top: 10px;
    right: 10px;
}
.app-container {
    max-width: 1530px;
    margin: 0 auto;
    background: #ebf4fa;
    border-radius: 12px;
    .apply-box {
        border-radius: 15px;
        .line {
            height: 22px;
            width: 5px;
            background: #277fd6;
        }
    }
}
</style>
